package com.zeno.okhttpsimple;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MainActivity
        extends AppCompatActivity
{

    private static final String BASE_URL = "http://www.baidu.com" ;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Logger.init("MainActivity") ;
    }

    /**
     * 按钮点击事件
     * @param view
     */
    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_ok_get:
                okHttpGet();
                break;
            case R.id.btn_ok_post:
                okHttpPost();
                break;
            case R.id.btn_ok_put:
                okHttpPut();
                break;
            case R.id.btn_ok_delete:
                okHttpDelete() ;
                break;
            case R.id.btn_ok_upload_file:
                okHttpUpload() ;
                break;
            case R.id.btn_ok_down_load:
                okHttpDownload() ;
                break;
        }
    }

    /**
     * 使用 OKHttp GET请求
     */
    private void okHttpGet() {
        // 1. 创建一个okhttpclient 客户端
        OkHttpClient client = new OkHttpClient() ;

        // 2. 创建一个RequestBuilder对象 ， 创建请求构建参数对象
        Request.Builder builder = new Request.Builder() ;
        builder.url(BASE_URL) ;
        // 3. 使用请求构造对象，构建一个Request对象
        Request request = builder.build() ;

        // 4. 创建一个请求调度 , 此时还没有进行网络请求
        Call call = client.newCall(request) ;

        // 5. 将请求调度加入到队列之中
        call.enqueue(new Callback()
        {
            // 网络访问失败
            @Override
            public void onFailure(Request request, IOException e)
            {
                Logger.e(e.getMessage());
            }
            // 网络访问成功
            @Override
            public void onResponse(Response response) throws IOException
            {
                Logger.i(response.body().string());
            }
        });

    }


    /**
     * 使用 OKHttp POST请求
     */
    private void okHttpPost() {
        // 1.创建一个okHttpClient对象
        OkHttpClient client = new OkHttpClient() ;
        // 2.创建一个请求参数构造对象
        Request.Builder builder = new Request.Builder();
        // 3.设置请求的URL地址
        builder.url("http://192.168.0.187:8080/test.php") ;
        // 4. 创建一个请求表单对象
        FormEncodingBuilder encodingBuilder = new FormEncodingBuilder() ;
        // 5. 设置请求表单参数
        encodingBuilder.add("name","xiaozhu");
        encodingBuilder.add("pwd","xiaozhu") ;
        // 6.设置请求构建器的请求方法为 post
        builder.post(encodingBuilder.build()) ;
        // 7.使用请求参数构造对象 ， 构造一个Request请求对象
        Request request = builder.build() ;
        // 8.建立一个新的调度器
        Call call = client.newCall(request) ;
        // 9.将调度器加入到请求队列中
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Request request, IOException e)
            {
                Logger.e(e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException
            {
                Logger.json(response.body().string());
            }
        });
    }

    /**
     * 使用 OKHttp put请求
     */
    private void okHttpPut() {
        OkHttpClient client = new OkHttpClient() ;

        Request.Builder builder = new Request.Builder();
        builder.url("http://192.168.0.187:8080/test.php") ;
        FormEncodingBuilder encodingBuilder = new FormEncodingBuilder() ;
        encodingBuilder.add("method","put") ;
        encodingBuilder.add("name", "小猪") ;
        encodingBuilder.add("change", "xiaozhu") ;
        builder.put(encodingBuilder.build()) ;

        Request request = builder.build();

        Call call = client.newCall(request);

        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Request request, IOException e)
            {
                Logger.e(e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException
            {
                Logger.json(response.body().string());
            }
        });
    }



    private void okHttpDelete() {
        OkHttpClient client = new OkHttpClient() ;

        Request.Builder builder = new Request.Builder();
        builder.url("http://192.168.0.187:8080/test.php") ;

        FormEncodingBuilder encodingBuilder = new FormEncodingBuilder() ;
        encodingBuilder.add("method","delete") ;
        encodingBuilder.add("id","3") ;
        encodingBuilder.add("option", "2") ;

        builder.delete(encodingBuilder.build()) ;

        Request request = builder.build();

        Call call = client.newCall(request);

        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Request request, IOException e)
            {
                Logger.e(e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException
            {
                Logger.json(response.body().string());
            }
        });
    }

    /**
     * 使用 okHttp 文件上传
     */
    private void okHttpUpload() {
        OkHttpClient client = new OkHttpClient() ;
        File file = new File(Environment.getExternalStorageDirectory(),"12.apk") ;
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        Map<String,String> map1 = new HashMap<>() ;
        Map<String,String> map2 = new HashMap<>() ;
        map1.put("Content-Discrption", "form-data; name=apk") ;
        map2.put("Content-Discrption", "form-data; name=apk;filename=12.apk") ;
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addPart(
                Headers.of(map1), RequestBody.create(null, "xiaozhu")).addPart(Headers.of(map2),
                fileBody).build();
        Request.Builder builder = new Request.Builder();
        builder.url("http://192.168.0.187:8080/test.php") ;
        builder.post(requestBody) ;

        Request request = builder.build();

        Call call = client.newCall(request);
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Request request, IOException e)
            {
                Logger.e(e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException
            {
                Logger.json(response.body().string());
            }
        });
    }


    /**
     *  使用 OkHttp 下载文件
     */
    private void okHttpDownload() {
        OkHttpClient client = new OkHttpClient() ;

        Request.Builder builder = new Request.Builder();
        builder.url("http://192.168.0.187:8080/12.apk") ;

        Request request = builder.build();

        Call call = client.newCall(request);

        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Request request, IOException e)
            {
                Logger.e(e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException
            {
                try{

                    InputStream inputStream = response.body().byteStream();
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream) ;
                    File file = new File(Environment.getExternalStorageDirectory(),"22.apk") ;
                    FileOutputStream outputStream = new FileOutputStream(file) ;

                    byte[] bytes = new byte[1024] ;
                    int len = 0 ;

                    while ( (len = bufferedInputStream.read(bytes)) != -1 ) {
                        outputStream.write(bytes,0,len);
                    }

                    outputStream.close();
                    inputStream.close();

                }catch(Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
